

import os
import shutil
from glob import glob
from get_config import *

def mymovefile(srcfile, dstpath):                       # 移动函数
    if not os.path.isfile(srcfile):
        print("%s not exist!" % (srcfile))
    else:
        fpath, fname = os.path.split(srcfile)             # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)                       # 创建路径
        shutil.move(srcfile, dstpath + fname)          # 移动文件
        #print("move %s -> %s" % (srcfile, dstpath + fname))

def get_retfns(fns):
    retfns = []
    for sfn in fns:
        retimgfn = sfn
        retimgfn = sfn.replace('_img.jpg', '_ret.jpg')
        retjsonfn = sfn.replace('_img.jpg', '_ret.json')
        for x in [retimgfn, retjsonfn]:
            if os.path.exists(x):
                retfns.append(x)
    
    retfns = list(set(retfns))
    return retfns

def move_fns(fns, dpath, product):
    mkdir(dpath)
    out = []
    for sfn in fns:
        fpath, fname = os.path.split(sfn)
        fname1 = fname.split('_')
        fname1[4] = product
        fname = '_'.join(fname1)
        dfn = f'{dpath}/{fname}'
        try:
            shutil.move(sfn, dfn)          # 移动文件
            out.append(dfn)
        except Exception as e:
            #print(e)
            pass

    return out
    
def move_ng_images(index, end, product, fns):
    outp = get_outp(index, end)
    s = get_time_stamp()
    dpath = f'{outp}/{s}_{product}_{index}'
    retfns = get_retfns(fns)
    out1 = move_fns(retfns, dpath, product)
    out = move_fns(fns, dpath, product)
    out += out1
    return out

def move_ng_images2(index, end, product, fns):
    if len(fns)==0:
        return fns
    out = move_ng_images(index, end, product, fns)
    return out

def test_mymovefile():
    src_dir = './'
    dst_dir = './move/'                                    # 目的路径记得加斜杠
    src_file_list = glob(src_dir + '*')                    # glob获得路径下所有文件，可根据需要修改
    for srcfile in src_file_list:
        mymovefile(srcfile, dst_dir)                       # 移动文件

def del_last_img(min_free = 1000000):
    progname = config['progname']
    root_path = f'{out_img_p}/{progname}'
    mkdir(root_path)
    total, used, free = shutil.disk_usage(root_path)
    aa = free/total
    print(f'del_last_img: free/total={aa:.3} {root_path}')
    if free>2000000:
        return 0
    li = os.listdir(root_path)
    li.sort()
    try:
        li = li[:10]
        for i in li:
            aa = f'{root_path}/{i}'
            if os.path.exists(aa):
                shutil.rmtree(aa)
            print(f'{aa} 删除成功')
    except Exception as e:
        print(e)
    
    return 1

def get_logger():
    from logging.handlers import TimedRotatingFileHandler
    log_fmt = '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'
    formatter = logging.Formatter(log_fmt)
    t = str(time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()))
    progname = config['progname']
    out_p = get_out_img_p()
    fh = TimedRotatingFileHandler(
        filename="%s/run_%s_%s.log" % (out_p, progname, t),
        when="H", interval=1,
        backupCount=72)
    fh.setFormatter(formatter)
    logging.basicConfig(level=logging.INFO)
    log = logging.getLogger()
    log.addHandler(fh)
    return log

get_logger()

class SafeCam():
    def __init__(self, cls, ip0 = None):
        self.ip0 = None
        self.cam = None
        self.cls = cls
        self.open(ip0)
    
    def open(self, ip0):
        if ip0 is not None:
            self.ip0 = ip0
            self.cam = self.cls(ip0)
            return 1

        return 0

    def close(self):
        if self.cam is not None:
            self.cam.close()
        return 0

    def getFrame(self):
        im = self.cam.getFrame()
        #if random.random()>0.5:
        #    im = None
        if im is None:
            print('cam reopen')
            self.close()
            self.cam = None
            self.open(self.ip0)
            im = self.cam.getFrame()
        
        return im




if __name__ == "__main__":
    test_mymovefile()
    # cv2.destroyAllWindows()
